<script lang="ts" setup>
import { Icon } from "@vicons/utils";
import { WechatOutlined } from "@vicons/material";
import { useUserStore } from "@/store/modules/user";
import { useRouter, useRoute } from "vue-router";
import { isMiniProgram } from "@/utils/mini-program";
import { buildParams } from "@/utils/utils";
import wx from "weixin-js-sdk";
import { showToast } from "@nutui/nutui";
import { getOSSURL } from "@/utils/utils";
import "@nutui/nutui/dist/packages/toast/style";

const userStore = useUserStore();
const router = useRouter();
const route = useRoute();

const config = {
  subtitle: "专业学车 轻松拿证",
  permissions: ["获取你的公开信息（昵称、头像等）"],
};

// 初始化驾校信息
const tenantInfo = computed(() => ({
  logo: getOSSURL(userStore.tenantInfo?.logoOssUrl) || "",
  title: userStore.tenantInfo?.schoolName || "",
}));

// 从微信登录页面返回回来的回调，带有token字段
const token = route.query["token"] as string;
if (token) {
  // 登录成功后的重定向
  userStore.refreshAuthByToken(token).then(() => {
    router.replace(userStore.shareInfo.targetPath);
  });
}

const inviterUid = userStore.shareInfo.userId as string;

/**
 * 小程序页面登录
 * @param inviterUid 邀请者id
 */
const loginByMiniProgram = async (inviterUid: string) => {
  console.log("小程序登录");

  const paramsStr = buildParams({
    uid: inviterUid,
  });

  wx.miniProgram.navigateTo({ url: `/pages/login/index?${paramsStr}` });
};

if (!token && isMiniProgram()) {
  loginByMiniProgram(inviterUid);
}

/**
 * 通过固定手机号登录，仅用于测试
 */
const loginByMobile = async () => {
  console.log("手机登录");

  const userStore = useUserStore();
  await userStore.login({
    mobile: "13727809535",
    password: "admin123",
  });
  router.replace(userStore.shareInfo.targetPath);
};

/**
 * 通过h5登录
 * @param inviterUid 邀请者id
 */
const loginByH5 = async (inviterUid: string) => {
  console.log("h5登录");

  const paramsStr = buildParams({
    uid: inviterUid,
  });

  const baseURL: string = import.meta.env.VITE_APP_BASE_URL;
  location.href = `${baseURL}/wx-auth/login?${paramsStr}`;
};

/**
 * 登录按钮点击
 */
const handleLogin = async () => {
  if (import.meta.env.DEV) {
    showToast.text("正在通过手机号登录...");
    await loginByMobile();
    return;
  }

  showToast.text("正在调起微信登录...");
  await loginByH5(inviterUid);
};
</script>

<template>
  <div class="h-screen bg-white flex flex-col items-center px-4">
    <!-- 驾校信息 -->
    <nut-image class="w-20 mt-20" :src="tenantInfo.logo" />
    <!-- <h1 class="mt-4 text-xl">{{ tenantInfo.title }}</h1> -->
    <p class="mt-1 text-gray">{{ config.subtitle }}</p>

    <hr class="w-full my-8" />

    <!-- 权限列表 -->
    <div class="w-full">
      <p class="w-full px-6 text-lg">申请获取以下权限，请确认是本人操作</p>
      <ul class="w-full mt-2 px-10 list-disc text-gray">
        <li v-for="item in config.permissions" :key="item">{{ item }}</li>
      </ul>
    </div>

    <!-- 登录按钮 -->
    <div class="w-full mt-15 px-6">
      <button
        class="w-full py-2.5 rounded-full text-white bg-green-5 border border-2 duration-300 active:bg-green-6 active:border-gray active:scale-105"
        @click="handleLogin"
      >
        <Icon class="text-3xl align-middle">
          <WechatOutlined />
        </Icon>
        <span class="inline-block ml-2 align-middle">微信授权登录</span>
      </button>
    </div>
  </div>
</template>
